﻿using JavaVirtualMachine.Attributes;
using JavaVirtualMachine.ConstantPoolItems;
using System;
using System.Collections.Generic;

namespace JavaVirtualMachine
{
    public struct MethodFrame
    {
        public readonly string MethodClass;
        public readonly string MethodDescriptor;
        public readonly string MethodName;
        public readonly MethodInfo Method;
        public readonly int BaseOffset;
        public readonly IEnumerator<MethodInfo>? NativeState;
        public Memory<int> GlobalStack;
        public int SP
        {
            get => GlobalStack.Span[BaseOffset + Method.MaxLocals];
            set => GlobalStack.Span[BaseOffset + Method.MaxLocals] = value;
        }

        public int IP
        {
            get => GlobalStack.Span[BaseOffset + Method.MaxLocals + 1];
            set => GlobalStack.Span[BaseOffset + Method.MaxLocals + 1] = value;
        }
        //Method.MaxStack+2 不加2会出现未知Bug,加2增加容错率
        public Span<int> Stack => GlobalStack.Span.Slice(BaseOffset + Method.MaxLocals + 2, Method.MaxStack);

        public MethodFrame(MethodInfo methodInfo, int baseOffset, IEnumerator<MethodInfo>? nativeState, Memory<int> globalStack)
        {
            Method = methodInfo;
            MethodClass = Method.ClassFile.Name;
            MethodDescriptor = Method.Descriptor; 
            MethodName= Method.Name;
            BaseOffset = baseOffset;
            NativeState = nativeState;
            GlobalStack = globalStack;
            SP = 0;
            IP = 0;
        }
    }
}
